package com.csdj.t309springboot.controller;
import com.csdj.t309springboot.common.CacheConstant;
import com.csdj.t309springboot.common.WebResult;
import com.csdj.t309springboot.common.WebResultMsgCode;
import com.csdj.t309springboot.entity.BlindBox;
import com.csdj.t309springboot.entity.IntegralRecord;
import com.csdj.t309springboot.entity.JigsawPuzzlePieces;
import com.csdj.t309springboot.entity.PiecesOfRecord;
import com.csdj.t309springboot.service.*;
import com.csdj.t309springboot.utils.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 盲盒表前端控制器
 * </p>
 *
 * @author 谭湛宇
 * @since 2022-01-14
 */
@RestController
@RequestMapping("/blind/box")
public class BlindBoxController extends BaseController{
    private Logger log = LoggerFactory.getLogger("blindBox");
    @Resource
    private RedisService redisService;
    @Resource
    private BlindBoxService blindBoxService;
    @Resource
    private IntegralRecordService integralRecordService;
    @Resource
    private PiecesOfRecordService piecesOfRecordService;
    @Resource
    private JigsawPuzzleService jigsawPuzzleService;
    @Resource
    private JigsawPuzzlePiecesService jigsawPuzzlePiecesService;
//    @Resource
//    private UserService userService;

    /**
     * 抽盲盒 , 要开启事务, 修改盲盒信息,减少用户的积分,新增碎片记录信息,新增积分记录信息
     * @param blindBoxId 盲盒编号
     * @param jigsawPuzzleId 拼图编号
     * @param times 单次抽盲盒次数,一次~五次,最多一次抽五个盲盒
     * @param request HttpServletRequest对象,用于获取用户编号
     * @return WebResult 返回固定的json数据格式
     */
    @GetMapping("/extractTheBlindBox")
    public WebResult extractTheBlindBox(int blindBoxId,
                                        int jigsawPuzzleId,
                                        int times,
                                        HttpServletRequest request){
//        redisService.getString(CacheConstant.HEADER_UID)
        int userId = getUid(request);
        log.info("getUid(request) userId="+userId);
        //盲盒碎片的位置
        String stringPiecesPosition =null;
        //随机生成碎片位置,碎片位置:第几号碎片
        if(times>1){//次数大于1次,
            if(times>5)//一次最多连续抽5个
                times=5;
            stringPiecesPosition = RandomUtil.getRandomNumber(times);
        }else{//异常情况,最少抽一次
            times = 1;//单抽一次
            stringPiecesPosition = RandomUtil.getRandomNumber(times);
        }
        /**
         * 设置盲盒信息 ;把抽取到的盲盒碎片存到数据库里,需要有 拼图id,盲盒id,用户id,碎片位置
         */
        log.info("stringPiecesPosition="+stringPiecesPosition);
        BlindBox blindBox = new BlindBox();
        blindBox.setBlindBoxId(blindBoxId);
        blindBox.setJigsawPuzzleId(jigsawPuzzleId);
        blindBox.setUserId(userId);

        String redisPiecesPosition = redisService.getString(CacheConstant.CACHE_PIECES_POSITION+userId);
        log.info("redisPiecesPosition="+redisPiecesPosition);
        //不是第一次抽盲盒碎片
        if( null !=redisPiecesPosition ){
            blindBox.setPiecesPosition(redisPiecesPosition+stringPiecesPosition);
        }else{//第一次抽盲盒碎片,redis里面为空
            blindBox.setPiecesPosition(stringPiecesPosition);
        }
        String[] splitStringPiecesPosition = stringPiecesPosition.split(",");
        log.info("jigsawPuzzleId="+jigsawPuzzleId+",+blindBoxId="+blindBoxId);
        /**
         * 设置积分记录信息并新增一条记录
         */
        IntegralRecord integralRecord = new IntegralRecord();
        integralRecord.setUserId(userId);
        integralRecord.setIntegralSource(CacheConstant.INTEGRAL_SOURCE_EXTRACT_BLIND_BOX);//来源:抽盲盒
        //积分变化(需要的积分) = 抽盲盒次数 times * 单次所需要的积分数量
        //查询盲盒表 需要的积分数量
        BlindBox blindBoxInfo = blindBoxService.getBlindBoxInfo(blindBoxId);

        //查询积分余额
        IntegralRecord integralRecordInfo = integralRecordService.getIntegralRecordInfoByUserId(userId);

        int integralChange = times * blindBoxInfo.getIntegralRequired();//抽盲盒需要的积分
        //判断余额是否足够抽盲盒;如果需要的积分大于积分余额
        log.info("integralRecordInfo.getIntegralBalance()="+integralRecordInfo.getIntegralBalance());
        if(integralChange>integralRecordInfo.getIntegralBalance()){
            return new WebResult(WebResultMsgCode.SUCCESS,"积分不足");
        }
        //将正整数转为负整数; 方式二: int positiveVal = 200;int negativeVal = (~(positiveVal - 1));
        integralRecord.setIntegralChange( -integralChange );

        integralRecord.setIntegralBalance( integralRecordInfo.getIntegralBalance() - times * blindBoxInfo.getIntegralRequired());
        int insertIntegralRecord = integralRecordService.insert(integralRecord);
        if(insertIntegralRecord<=0){
            return new WebResult(WebResultMsgCode.SUCCESS,"新增积分记录失败");
        }
        //碎片数量
        /**
         * 增加碎片记录信息; 循环向碎片记录表新增信息
         */
        for (String strPiecesPosition : splitStringPiecesPosition){
            PiecesOfRecord piecesOfRecord = new PiecesOfRecord();
            piecesOfRecord.setJigsawPuzzleId(jigsawPuzzleId);
            piecesOfRecord.setBlindBoxId(blindBoxId);
            piecesOfRecord.setUserId(userId);
            log.info("for() strPiecesPosition="+strPiecesPosition);
            //判断如果碎片位置存在, 则修改增加碎片数量, 否则新增拼图碎片记录
            piecesOfRecord.setPiecesPosition(Integer.parseInt(strPiecesPosition));
            /**
             *  向拼图碎片表新增或修改记录
             */
            JigsawPuzzlePieces jigsawPuzzlePieces = new JigsawPuzzlePieces();
            jigsawPuzzlePieces.setBlindBoxId(blindBoxId);
            jigsawPuzzlePieces.setJigsawPuzzleId(blindBoxId);
            jigsawPuzzlePieces.setUserId(userId);
            jigsawPuzzlePieces.setPiecesPosition(Integer.parseInt(strPiecesPosition));
            //设置碎片数量
            jigsawPuzzlePieces.setNumberOfPuzzlePieces(1);

            int insertPiecesOfRecord = piecesOfRecordService.insert(piecesOfRecord);
            if( !(insertPiecesOfRecord>0) ){
                return new WebResult(WebResultMsgCode.FAIL,"insertPiecesOfRecord失败");
            }
            //修改
            int insertJigsawPuzzlePieces = jigsawPuzzlePiecesService.insert(jigsawPuzzlePieces);
            if( !(insertJigsawPuzzlePieces>0) ){
                return new WebResult(WebResultMsgCode.FAIL,"失败");
            }

        }
        /**
         * 执行修改盲盒信息
         */
        boolean result = blindBoxService.updateById(blindBox);
        //如果修改成功,保存拼图碎片位置到redis里面
        if(result){
            redisService.setObject(CacheConstant.CACHE_PIECES_POSITION+userId,stringPiecesPosition);
            return new WebResult(WebResultMsgCode.SUCCESS).putData("stringPiecesPosition",stringPiecesPosition);
        }else{
            return new WebResult(WebResultMsgCode.FAIL,"失败");
        }
    }
    /**
     * 根据编号查询详情
     * @param blindBoxId
     * @param request
     * @return实体类对象
     */
    @GetMapping("/getBlindBoxInfo")
    public WebResult getBlindBoxInfo(@RequestParam int blindBoxId, HttpServletRequest request){
        log.info("getBlindBoxInfo() blindBoxId="+blindBoxId);
        BlindBox blindBox = blindBoxService.getBlindBoxInfo(blindBoxId);
        if(null!=blindBox){
            return new WebResult(WebResultMsgCode.SUCCESS).putData("entity",blindBox);
        }
        return new WebResult(WebResultMsgCode.FAIL);
    }
    @GetMapping("/getAllBlindBox")
    public WebResult getAllBlindBox(){
        List<BlindBox> list = blindBoxService.getAllBlindBox();
        if(null!=list){
            return new WebResult(WebResultMsgCode.SUCCESS).putData("list",list);
        }
        return new WebResult(WebResultMsgCode.FAIL);
    }
}
